using System;
using WCFFactoryCaching.Common;
using System.Threading;
using ACorns.WCF.DynamicClientProxy;
using System.ServiceModel;

//using ACorns.WCF.DynamicClientProxy.Pool;

namespace WCFFactoryCaching.Client
{
	class Program
	{
		static void Main(string[] args)
		{
			//ProxyConnectionPool.EnableConnectionPool = true;

			Console.WriteLine("Client ...");

			Thread.Sleep(1000);	// let the server start
			Random rand = new Random(7);

			// get an IService instance connected to the EndPoint "Service1" that is wrapped and can be reused after faults.
			for (int i = 0; i < 10; i++)
			{
				try
				{
					IService1 service = WCFClientProxy<IService1>.GetReusableFaultUnwrappingInstance("Service1");
					using (service as IDisposable)
					{
						service.MyOperation1("a", 0);
					}

					// Call the server. Every second call will fail but we can still reuse the proxy.
					Console.WriteLine(i + " ClientTime:" + DateTime.Now.ToString("HH:MM:ss:ffff") + " result -> " + service.MyOperation1("a", 0));
				}
				catch (InvalidOperationException ex1)
				{
					Console.WriteLine(i + " " + ex1.Message);
				}
				catch (FaultException<InvalidOperationException> fex1)
				{
					Console.WriteLine(i + " " + fex1.Detail.Message);
				}
				catch (FaultException<Exception> fex2)
				{
					Console.WriteLine(i + " " + fex2.Detail.Message);
				}

				Thread.Sleep(100 * rand.Next(20));
			}
			
			//ProxyConnectionPool.Current.Dispose();

			Console.WriteLine("Done...");
			Console.ReadKey();
		}
	}
}
